import { Provide, Inject } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Brackets, Repository } from 'typeorm';
import { WeiboCommentsEntity } from '../entity/blogComment';
import { WeiboBlogService } from '../service/weibo';
import { UserInfoService } from '../../user/service/info';
import { Tree } from '../../../comm/tree';
import { UserInfoEntity } from '../../user/entity/info';
import { WeiboBlogCommentLoveEntity } from '../entity/blogCommentLove';
import { UserActionLogService } from '../../user/service/log';
/**
 * 描述
 */
@Provide()
export class WeiboCommentsService extends BaseService {
  @InjectEntityModel(WeiboCommentsEntity)
  weiboCommentsEntity: Repository<WeiboCommentsEntity>;

  @Inject()
  blogSrv: WeiboBlogService;

  @Inject()
  userSrv: UserInfoService;

  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;

  @InjectEntityModel(WeiboBlogCommentLoveEntity)
  weiboBlogCommentLoveEntity: Repository<WeiboBlogCommentLoveEntity>;

  
  @Inject()
  userActionLogSrv: UserActionLogService;

  @Inject()
  tree: Tree;

  async addComment(params: any) {
    const { blogId, userId, content, parentCommentId, replyCommentId } = params;
    const blog = await this.blogSrv.info(blogId);
    if (!blog) {
      throw new CoolCommException('博客不存在或已删除~');
    }
    const user = await this.userSrv.info(userId);
    const ip_addr= await this.userActionLogSrv.getUserIpAddr(
      user.id
    );
    const comment = new WeiboCommentsEntity();
    // 当前评论的用户名字
    comment.userName = user.nickname;
    comment.content = content;
    comment.userId = user.id;
    comment.blogId = blog.id;
    comment.ipAddr = ip_addr;

    // 判断是否用户本人
    if (user.id == blog.userId) {
      comment.contentFlag = 1;
    }
    // 评论的回复
    if (parentCommentId) {
      // 评论等级
      const comInfo = await this.info(parentCommentId);
      comment.commentLevel = 2;
      comment.parentCommentId = parentCommentId;
      comment.parentCommentUserId = comInfo.userId;
    }

    // 回复的回复
    if (replyCommentId) {
      comment.commentLevel = 2;
      const comInfo = await this.info(replyCommentId);
      comment.replyUserName = comInfo.userName;
      comment.replyCommentId = comInfo.id;
      comment.replyCommentUserId = comInfo.userId;
    }

    return await this.weiboCommentsEntity.save(comment);
  }

  async info(id: any) {
    return this.weiboCommentsEntity.findOne({ id });
  }

  /**
   * 评论分页
   * @param param0
   * @returns
   */
  async findCommentList({
    blogId,
    commentLevel,
    parentCommentId,
    order = 'updateTime',
    sort = 'DESC',
    page = 1,
    size = 10,
  }: any) {
    return await this.weiboCommentsEntity
      .createQueryBuilder('a')
      .select('a.*,b.headimgurl,b.nickname')
      .where(
        new Brackets(qb => {
          qb.where('1 = 1');
          if (blogId) {
            qb.andWhere({ blogId });
          }
          if (commentLevel) {
            qb.andWhere({ commentLevel });
          }
          if (parentCommentId) {
            qb.andWhere({ parentCommentId });
          }
        })
      )
      .leftJoin(UserInfoEntity, 'b', 'a.user_id = b.id')
      .groupBy('a.id')
      .offset(parentCommentId ? page==1?0: (page - 1) * size : (page - 1) * size)
      .limit(size)
      .orderBy('a.topStatus', 'DESC')
      .addOrderBy('a.' + order, sort == 'DESC' ? 'DESC' : 'ASC')
      .getRawMany();
  }

  /**
   * 查询当前评论数量
   * @param blogId
   * @returns 数量
   */
  async findCommentCount(blogId: number) {
    return await this.weiboCommentsEntity.count({ blogId });
  }

  
  /**
   * 批量查询查询当前评论数量
   * @param blogId
   * @returns 数量
   */
  async findCommentListCount(arr: [any]) {
    if (arr && arr.length) {
      arr.map(async v=>{
        v.count_comment =  await this.findCommentCount(v.id);
      })
    }
    return arr;
  }

  /**
   * 查询当前评论的点赞数量
   * @param blogId
   * @returns 数量
   */
  async findCommentLoveCount(blogId: number, commentId: number) {
    return await this.weiboBlogCommentLoveEntity.count({ blogId, commentId });
  }

  async love({ blogId, userId, commentId }: any) {
    const commentsLove = await this.weiboBlogCommentLoveEntity.findOne({
      where: { blogId, userId, commentId },
    });

    const comments = await this.weiboCommentsEntity.findOne({
      where: { id: commentId, blogId },
    });

    let praiseNum = 0;
    if (comments.praiseNum && comments.praiseNum !== null) {
      praiseNum = Math.trunc(comments.praiseNum);
    }

    if (commentsLove) {
      praiseNum--;
      await this.weiboBlogCommentLoveEntity
        .createQueryBuilder()
        .delete()
        .where({ blogId, userId, commentId })
        .execute();
      await this.weiboCommentsEntity
        .createQueryBuilder()
        .update()
        .where({ id: commentId, blogId })
        .set({ praiseNum })
        .execute();
      return 'cancel';
    } else {
      praiseNum++;
      await this.weiboCommentsEntity
        .createQueryBuilder()
        .update()
        .where({ id: commentId, blogId })
        .set({ praiseNum: Math.trunc(comments.praiseNum) + 1 })
        .execute();
      await this.weiboBlogCommentLoveEntity.save({ blogId, userId, commentId });
      return 'up';
    }
  }

  /**
   * 查询当前评论 用户是否 点赞
   * @param blogId
   * @param userId
   * @returns
   */
  async hasLove({ blogId, userId, commentId }: any) {
    const res = await this.weiboBlogCommentLoveEntity
      .createQueryBuilder()
      .where({ blogId, userId, commentId })
      .getOne();
    return res ? true : false;
  }
}
